using System.Runtime.InteropServices;

namespace BlazorApp1;

public class UserService
{
    private int _hDev = 0;
    public UserService()
    {
        IntPtr errMsgBuffer = Marshal.AllocHGlobal(256);
        
        try
        {
            // 调用非托管函数
            _hDev = DC_OpenDevice(errMsgBuffer);
            
            // 获取错误消息
            string errMsg = Marshal.PtrToStringAnsi(errMsgBuffer);
            
            // 打印结果和错误消息
            Console.WriteLine($"Result: {_hDev}");
            Console.WriteLine($"Error Message: {errMsg}");
        }
        finally
        {
            // 释放分配的内存
            Marshal.FreeHGlobal(errMsgBuffer);
        }
    }

    public string ReadCard()
    {
        IntPtr errMsgBuffer = Marshal.AllocHGlobal(256);
        IntPtr cardBuffer = Marshal.AllocHGlobal(256);
        var msg = "";
        try
        {
            // 调用非托管函数
            var result = DC_GetUnionpayCardNo(_hDev, cardBuffer, errMsgBuffer);
            
            // 获取错误消息
            msg = Marshal.PtrToStringAnsi(cardBuffer);
            string errMsg = Marshal.PtrToStringAnsi(errMsgBuffer);
            
            // 打印结果和错误消息
            Console.WriteLine($"Result: {_hDev}");
            Console.WriteLine($"Error Message: {errMsg}");
        }
        finally
        {
            // 释放分配的内存
            Marshal.FreeHGlobal(errMsgBuffer);
            Marshal.FreeHGlobal(cardBuffer);
        }

        return msg;
    }
    
    public const string DLL_NAME = "DCCardReader";
    
    [DllImport(DLL_NAME, CallingConvention = CallingConvention.StdCall)]
    public static extern int DC_OpenDevice(IntPtr errMsg);
    
    [DllImport(DLL_NAME, CallingConvention = CallingConvention.StdCall)]
    public static extern int DC_GetUnionpayCardNo(int hDev, IntPtr unionpayCardNo, IntPtr errMsg);
}